﻿using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Timer = System.Threading.Timer;

namespace QWScreenPanel.Model
{
    /// <summary>
    /// QWPress
    /// </summary>
    public partial class QWPress : UserControl
    {
        private string[] _files;
        private int _imageCount;
        private int _imagePos;
        private Timer _timer;

        /// <summary>
        /// Initializes a new instance of the <see cref="QWPress"/> class.
        /// </summary>
        public QWPress()
        {
            _files = Directory.GetFiles("./PressImages/");
            _imageCount = _files.Count();
            _imagePos = 0;

            InitializeComponent();
            panel1.BackgroundImageLayout = ImageLayout.Stretch;
            _timer = new Timer(LoadImages, null, 100, 15000);

        }

        /// <summary>
        /// Loads the images.
        /// </summary>
        /// <param name="stateinfo">The stateinfo.</param>
        private void LoadImages(object stateinfo)
        {
            try
            {
                if (InvokeRequired)
                {
                    var o = new DelegateThis(LoadImages);
                    Invoke(o, stateinfo);
                }
                else
                {
                    panel1.BackgroundImage = new Bitmap(_files[_imagePos]);
                    lblCount.Text = string.Format("{0}/{1}", _imagePos + 1, _files.Count());

                    _imagePos++;

                    if (_imagePos >= _files.Count())
                    {
                        _files = Directory.GetFiles("./PressImages/");
                        _imageCount = _files.Count();
                        _imagePos = 0;
                    }

                    Application.DoEvents();
                }
            }
            catch
            {
            }
        }

        #region Nested type: DelegateThis

        /// <summary>
        /// DelegateThis
        /// </summary>
        private delegate void DelegateThis(object stateinfo);

        #endregion
    }
}